<template>
  <ul v-if="totalPage > 1" class="pagination">
    <li :class="{ disabled: internalCurrentPage === 1 }">
      <a href="javascript:;" @click="changePage(internalCurrentPage - 1)">«</a>
    </li>
    <li v-for="(n,index) in totalPage" :key="index" :class="{ active: internalCurrentPage === n }">
      <a href="javascript:;" @click="changePage(n)">{{ n }}</a>
    </li>
    <li :class="{ disabled: internalCurrentPage === totalPage }">
      <a href="javascript:;" @click="changePage(internalCurrentPage + 1)">»</a>
    </li>
  </ul>
</template>

<script>
export default {
  name: "Pagination",
  props: {
    // 当前页
    currentPage: {
      type: Number,
      default: 1
    },
    // 数据总数
    total: {
      type: Number,
      required: true
    },
    // 每条页数
    pageSize: {
      type: Number,
      default: 7,
      validator: value => value > 0
    },
    // 当前页改变后的回调
    onPageChange: {
      type: Function,
      default: () => {}
    }
  },

  data() {
    return {
      // 组件内的当前页
      internalCurrentPage: 1
    };
  },

  computed: {
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    }
  },

  watch: {
    currentPage: {
      //该回调将会在侦听开始之后被立即调用
      immediate: true,
      //特定的接口方法
      handler(page) {
        // 更新组件内的当前页，为父组件上 currentPage 的当前值
        this.internalCurrentPage = page;
      }
    }
  },

  methods: {
    changePage(page) {
      if (
        page === this.internalCurrentPage ||
        page < 1 ||
        page > this.totalPage
      )
        return;
      // 不是当前页则触发回调,回调父类进来的函数
      this.onPageChange(page);
    }
  }
};
</script>
<style>
</style>
